<template>
    <div class="pt-8">
        <div class="pb-2">
            <button class="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600" @click="save">保存</button>
        </div>
        <MdEditor v-model="content" @onUploadImg="onUploadImg" :toolbars="toolbars" :footers="[]" :preview="false"
            style="height: auto; background-color: transparent !important;">
        </MdEditor>
    </div>

</template>

<script setup>

import { MdEditor } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import 'md-editor-v3/lib/preview.css';

const toolbars = reactive([])

const props = defineProps({
    content: {
        type: String,
        required: true
    }
})
const content = ref(props.content)

// 接收父组件的content
watch(
    () => props.content,
    (new_value) => {
        content.value = new_value
    }
)

// 向父组件传递content
const emit = defineEmits(['update'])

watch(
    () => content.value,
    (newValue) => {
        emit('update', newValue)
    }
)

const { Message } = useMessageBox()
const { saveMarkdown } = useApi()

const save = async () => {
    const response = await saveMarkdown({
        content: content.value,
        path: useState('path').value
    })
    if (response.code != 200) {
        Message.error(response.msg)
    } else {
        Message.success('保存成功', { width: 'auto' })
        emit('update', content.value)
    }
}

const { uploadImage } = useApi()

const onUploadImg = async (files, callback) => {
    const res = await Promise.all(
        files.map((file) => {
            return new Promise((rev, rej) => {
                const form = new FormData();
                form.append('file', file);
                form.append('path', useState('path').value)

                const response = uploadImage(
                    form, 
                    {
                        'Content-Type': 'multipart/form-data'
                    }
                ).then((res) => {
                    if (res.code == 200) {
                        rev(res)
                    } else {
                        rej(res.msg)
                    }
                })
                
                
                // rev({
                //     data: {
                //         url: 'aaa.jpg'
                //     }
                // })
            });
        })
    );

    // 方式二
    callback(
        res.map((item) => ({
            url: item.data.url,
            alt: 'alt',
            title: ''
        }))
    );
}


</script>